<!-- 月计划 -->
<template>
  <!-- 主内容区 -->
  <a-row :gutter="10" class="page-height">
    <!-- 树搜索 -->
    <a-col :span="6" class="permission-collapsed" :class="{ 'permission-tree-collapsed': collapsed }">
      <a-card :style="{ border: collapsed ? 'none' : 'border: 1px solid #e8e8e8' }" class="page-height-tree">
        <title-name title="组织架构" />
        <PermissionTreeOrganization :collapsed.sync="collapsed" @select="handleSelect" />
      </a-card>
    </a-col>
    <a-col :span="18" class="permission-collapsed page-height-list-wrapper" :style="collapsed ? 'width:calc(100% - 10px)' : ''">
      <!-- 搜索 -->
      <searchData :search-data="searchOption" :row-count="3" @search="search" />
      <!-- 搜索 -->
      <a-card class="page-height-list">
        <list-table
          ref="table"
          size="default"
          :rowKey="'id'"
          :columns="columns"
          :request="loadData"
          :isInit="false"
          :filter-data="filterData"
          :exportPermission="{ select: 'pm_065_exp_03', all: 'pm_065_exp_03' }"
          :exportConfig="{ use: true, select: $route.meta.title, all: $route.meta.title }"
          @exportSelect="exportExcel"
          @exportAllNoRequest="exportExcel"
        >
          <MoreButton slot="operation" slot-scope="text, record">
            <a v-btnPermission="'pm_065_loo_01'" @click="handleDetail(record)">查看</a>
            <a v-if="hideBuquBtn() && [0, 3].includes(record.auditStatus)" v-btnPermission="'pm_065_edi_02'" @click="handleEdit(record)">编辑</a>
            <a v-if="!(record.warningNum === 1 && record.auditStatus === 0)" @click="$bus.$emit('showApprovalDetailsDialog', record.id)">审批信息</a>
          </MoreButton>
        </list-table>
      </a-card>
    </a-col>
  </a-row>
</template>
<script>
import PermissionTreeOrganization from '@/components/businessComponents/PermissionTreeOrganization'
import overdueNodeManagement from '@/api/construction/overdueNodeManagement'

import { searchOption, columns, nodeStatusList, auditStatusList } from './model.js'

export default {
  name: 'overdueNodeManagementWeekPlan',
  components: {
    PermissionTreeOrganization
  },
  data() {
    return {
      // 收缩展开树
      collapsed: false,
      //组织架构选中项
      select: {},
      // 查询参数
      searchData: {},
      // 搜索选项
      searchOption,
      // 表头
      columns,
      // 导出表头循环字段
      exportKey: [
        {
          title: '次预警的逾期原因',
          key: 'reason'
        },
        {
          title: '次预警的调整后计划完成时间',
          key: 'adjustCompletionTime'
        },
        {
          title: '次预警的保障措施',
          key: 'measure'
        }
      ],
      defaultMonth:'', //当前默认年月
      //表格数据加载
      loadData: async q => {
        const obj = {}
        const searchQuery = {
          orgSet: [],
          projectSet: []
        }
        this.searchData.belongMonth =  this.searchData.belongMonth || this.defaultMonth;
        try {
          // if (!this.select) {
          //   return
          // }
          // 二级-分公司id
          if (this.select?.tageCode === 'BC') {
            searchQuery.orgSet = [this.select.orgId]
          }
          // 三级-项目id
          if (this.select?.tageCode === 'PD') {
            searchQuery.projectSet = [this.select.projectId]
          }
          let searchData = Object.assign(q, { query: { searchQuery, ...this.searchData } })
          const res = await overdueNodeManagement.overdueNodeMonthPage(searchData)
          if (res.code === 200) {
            return { code: 200, data: res.data, ...res }
          } else {
            this.customColumns = null
            return { code: 200, data: [] }
          }
        } catch (error) {
          console.log(error)
        }
      }
    }
  },
  created() {
    const idx = searchOption.findIndex(item => item.value === 'belongMonth')
    this.defaultMonth =  this.$dateFormat(new Date(),'M')
    this.searchOption[idx].attr.defaultValue = this.defaultMonth;
  },
  methods: {
    /**
     * @description:
     * @param {objec} val 搜索数据
     * @return {void}
     */
    search(val = void 0) {
      this.searchData = val || this.searchData
      this.$refs.table.refresh(true)
    },
    /**
     * @description: 树选中
     * @param {object} node 节点对象
     * @return {void}
     */
    handleSelect(node) {
      this.select = node
      this.search()
    },
    /**
     * @description: 查看
     * @param {object} record 行数据
     * @return {void}
     */
    handleDetail(record) {
      this.$router.push({
        path: `/construction/constructionSchedule/overdueNodeManagement/operation`,
        query: {
          id: record.id,
          type: 'detail',
          from: 'monthPlan'
        }
      })
    },
    /**
     * @description: 编辑
     * @param {object} record 行数据
     * @return {void}
     */
    handleEdit(record) {
      this.$router.push({
        path: `/construction/constructionSchedule/overdueNodeManagement/operation`,
        query: {
          id: record.id,
          type: 'update',
          from: 'monthPlan'
        }
      })
    },
    /**
     * @description: 导出字段值过滤
     * @param {array} datas 列表数据
     * @return {array}
     */
    filterData(datas) {
      const list = this.$clone(datas)
      return list.map((item, index) => {
        item.index = index + 1
        item.nodeStatus = nodeStatusList.find(el => el.value == item.nodeStatus)?.label || ''
        item.auditStatus = auditStatusList.find(el => el.value === item.auditStatus)?.label || ''
        return item
      })
    },
    /**
     * @description: 导出excel
     * @param {array} data 选中项
     * @return {void}
     */
     async exportExcel(data) {
      this.$refs.table.loadingExport = true
      const searchQuery = {
        orgSet: [],
        projectSet: []
      }
      // 二级-分公司id
      if (this.select?.tageCode === 'BC') {
        searchQuery.orgSet = [this.select.orgId]
      }
      // 三级-项目id
      if (this.select?.tageCode === 'PD') {
        searchQuery.projectSet = [this.select.projectId]
      }
      try {
        const res = await overdueNodeManagement.overdueNodeMonthExcel({
          needCount: false,
          query: {
            searchQuery,
            ...this.searchData,
            // 全选传空数组
            idList: Array.isArray(data) ? data.map(el => el.id) : []
          }
        })
        console.log(res)
        this.handleDownload(res)
      } catch (error) {
        console.log(error)
      } finally {
        this.$refs.table.loadingExport = false
      }
    },
    /**
     * @description: 下载
     * @return {void}
     */

    handleDownload(res) {
      const blob = new Blob([res.data])
      const filename = decodeURIComponent(res.headers['content-disposition'].split('filename=')[1])
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = filename // 获取文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放blob对象
    }
  }
}
</script>
<style lang="less" scoped></style>
